import { Next } from 'koa';
import ioredis from 'ioredis';
import { KoaContext } from '@/types/koa';

import {
  generateToken,
} from '@/tools/token';

// ? 生成登录token
export const generateLoginToken = ({
  redisDB,
}: {
  redisDB: ioredis,
}) => async (ctx: KoaContext, next: Next) => {
  const { user } = ctx.state;
  const payload = {
    id: user?.id,
    account: user?.account,
  };

  const access_token = await generateToken(payload, process.env.ACCESS_TOKEN_SECRET as string, '1h');
  const refresh_token = await generateToken(payload, process.env.REFRESH_TOKEN_SECRET as string, '7d');

  // ? token存储redis限制失效token
  redisDB.hmset(`login_token_${user?.account}`, {
    access_token,
    refresh_token,
  });
  redisDB.expire(`login_token_${user?.account}`, 60 * 60 * 24 * 7);

  ctx.cache['login_token'] = {
    access_token,
    refresh_token,
  };

  await next();
};
